layui.use(function(){
    layer = layui.layer;
    var util = layui.util;
    var upload = layui.upload;
      var $ = layui.$;
      $(document).on('dblclick', 'img', function(){
        const srcimgdbclick = this.src;
        layer.photos({
            photos: {
              "title": "图片详情",
              "start": 0,
              "data": [
                {
                  "alt": "图片详情",
                  "pid": 1,
                  "src": srcimgdbclick,
                },
              ]
            }
          });
        });
}); 
/****样式*/
const varible_qjstyle_ys = `<style>input{background-color:#f7f7f7;border:1px solid #dcdcdc;padding:10px;border-radius:4px;font-size:16px;color:#333333;transition:background-color 0.3s ease}.container:hover{box-shadow:0 6px 12px rgba(0,0,0,0.15)}input:hover{background-color:#eaeaea}button{padding:10px 20px;background-color:#007bff;color:white;border:none;border-radius:4px;font-size:16px;cursor:pointer;transition:background-color 0.3s ease,transform 0.2s ease}textarea{background-color:#f7f7f7;border:1px solid #dcdcdc;padding:10px;border-radius:4px;font-size}
</style>`;
const userid_inmy = sessionStorage.getItem('exam_userid_forget');
/******ai-辅助 */
function helpful_fixjsonstring(jsonString) {
    let fixedString = jsonString.replace(/\n/g, '').replace(/\s+/g, ' ');
    try {
      let parsed = JSON.parse(fixedString);
      return parsed;
    } catch (error) {
      console.error('修复后的字符串仍然不是有效的JSON:', error);
      return null;
    }
  }
function helpful_ai_tochecktheanser(param1, param2, param3) {
    var param3a = '0-'+param3;
    var formData = new FormData();
            formData.append('param1', param1);
            formData.append('param2', param2);
            formData.append('param3', param3a);
            formData.append('param4',userid_inmy); //userid
            fetch('/yhdexbox_10/ai/getscore.php', {
          method: 'POST',
          body: formData
      })
      .then(function (response) {
          return response.json();
      }).then(function (data) {
        if (data.code === 200) {
            layer.msg('处理完毕');
            var jsond = helpful_fixjsonstring(data.data);
            document.getElementById('btdf_ai').value = jsond.score;
            document.getElementById('btyj_ai').value = jsond.comment;
            document.getElementById('buttons_ai').disabled = false;
        }else{
            layer.msg('处理失败'+data.data, {icon: 5});
            document.getElementById('buttons_ai').disabled = false;
            return 0;
        }
   })
}
/********************ai-辅助 */
let nowmenushowbything2 = null;
var jsonqjtoputin = null;
function point_tktcheck(jsonr_rcdata){ //单题-填空
    var data = jsonr_rcdata;
    var divs = document.querySelectorAll('div[id^="question_tkt"]');
    divs.forEach(function(div) {
        var tystatus = div.getAttribute('tystatus');
        var inputs = div.querySelectorAll('input');
        inputs.forEach(function(input) {
            var inputid = input.id;
            if (data[tystatus] && (data[tystatus]).find(obj => obj.hasOwnProperty(inputid))[inputid]) {
                if (input.value === (data[tystatus]).find(obj => obj.hasOwnProperty(inputid))[inputid]) {
                    div.style.backgroundColor = '#e0f7ed'; 
                    div.setAttribute('ghj','t');
                }else{
                    div.style.backgroundColor = '#ffebee';
                    div.setAttribute('ghj','f');
                    var newbu = x_point_newbutt('查看解析',function(){
                        helpful_answer_totellanyone(div.getAttribute('tystatus'));
                    });
                    div.appendChild(newbu);
                }
            }
        });
    });
}
function setting_point(){
    var quesyaks = document.querySelector(`[tystatus="${nowmenushowbything2}"]`);
    layer.open({
        type: 1, 
        area: ['500px', '300px'],
        title: '设置分数',
        shade: 0.6, 
        shadeClose: true, 
        maxmin: true, 
        anim: 0, 
        content: ` 
    ${varible_qjstyle_ys}
        <label for="btdf">本题得分</label>
        <input type="text" id="btdf" value="" >
        </br>
         <label for="btdfz">本题分数</label>
        <input type="text" id="btdfz" value="" >
            <button id="buttons"  type="button">修改</button>`,
        success: function (layero, index) {
            var dondothisdebug = false;
            document.getElementById('btdf').value = quesyaks.getAttribute('btdf');
            document.getElementById('btdfz').value = quesyaks.getAttribute('btdfz');
            if(quesyaks.getAttribute('ghj')==='f'){
                document.getElementById('btdf').value = 0;
                document.getElementById('btdf').disabled = true;
            }
            if(quesyaks.getAttribute('ghj')==='t'){
                dondothisdebug = true;
                document.getElementById('btdf').disabled = true;
            }
            document.getElementById('buttons').onclick = function () {
                if(dondothisdebug){
                    document.getElementById('btdf').value = document.getElementById('btdfz').value;
                }
                if(document.getElementById('btdf').value === '' || document.getElementById('btdfz').value === ''){
                    layer.msg('请先输入分数');
                    return;
                }
                if(Number(document.getElementById('btdf').value) > Number(document.getElementById('btdfz').value)){
                    layer.msg('得分分值不能大于本题分数');
                    return;
                }
                quesyaks.setAttribute('btdf', document.getElementById('btdf').value);
                quesyaks.setAttribute('btdfz', document.getElementById('btdfz').value);
                if((quesyaks.querySelector('h3').innerText).split('(')){
                    quesyaks.querySelector('h3').innerText = quesyaks.querySelector('h3').innerText.split('(')[0]+'('+document.getElementById('btdf').value+'/'+document.getElementById('btdfz').value+'分)';
                }else{
                    quesyaks.querySelector('h3').innerText = quesyaks.querySelector('h3').innerText+'('+document.getElementById('btdf').value+'/'+document.getElementById('btdfz').value+'分)';
                }
                layer.close(index);
            }
        }
      });
}
function uploads_url_canvas_jx(fieldsArray){ //避免报错,在解析时
    let uploadsIndex = fieldsArray.indexOf('/uploads');
    if (uploadsIndex !== -1) {
        return fieldsArray.substring(uploadsIndex);
    }else{
        return fieldsArray;
    }
}
function fillfromdatajson_notarray(fieldsArray,typeStatus){ //特殊题目解析
    let zjget = document.getElementById(typeStatus);
    if (zjget.tagName === 'CANVAS') { //解析后是否为canvas?
        var img = document.createElement('img');
        img.id = typeStatus;
        fieldsArray = uploads_url_canvas_jx(fieldsArray);
        img.src = fieldsArray;
        zjget.parentNode.replaceChild(img, zjget);
    }
}
function fillfromdatajson(jsonData) { //填充
    for (const typeStatus in jsonData) {
      if (jsonData.hasOwnProperty(typeStatus)) {
        const fieldsArray = jsonData[typeStatus];
        if(!Array.isArray(fieldsArray)) { 
            fillfromdatajson_notarray(fieldsArray,typeStatus)   //非array,特殊题目        
            continue;
        }
        fieldsArray.forEach(fields => {
          for (const key in fields) {
            if (fields.hasOwnProperty(key)) {
              const element = document.getElementById(key);
              if (element) {
                element.value = fields[key];
                element.readOnly = true;
                if (element.type === 'checkbox' || element.type === 'radio') {
                  if (fields[key] && typeof fields[key] === 'string' && fields[key].endsWith(':checked')) {
                    element.checked = true;
                  } else {
                    element.checked = false;
                  }
                  element.disabled = true;
                elsiftofuckthisisright(element);
                }
              }
                }}
          });
        }
    }
  }
  var elsmentff = '';
  function elsiftofuckthisisright(element) {
    elsmentff = element.parentElement.parentElement.parentElement;
    var chats = elsmentff;
    if(element.type === 'radio'){
        if(element.getAttribute('style') === 'background-color: rgb(0, 140, 255);' && element.getAttribute('typeos') === 'answer' && element.checked === true){
            if(elsmentff.getAttribute('ok') !== 'right'){
                elsmentff.setAttribute('ok', 'right');
                element.parentElement.parentElement.setAttribute('don', 'right');
                elsmentff.style.backgroundColor = '#e0f7ed';
                elsmentff.setAttribute('ghj','t');
            }
        }else{
            if(elsmentff.getAttribute('ok') !== 'right'){
                elsmentff.setAttribute('ok', 'right');
                element.parentElement.parentElement.setAttribute('don', 'right');
                elsmentff.style.backgroundColor = '#ffebee';
                elsmentff.setAttribute('ghj','f');
                var newbu = x_point_newbutt('查看解析', function (event) {
                    helpful_answer_totellanyone((chats).getAttribute('tystatus'));
                    event.stopPropagation();
                });
                elsmentff.appendChild(newbu);
            }
          
        }
    }
}
function allcheckboxzdpg(){
    document.querySelectorAll('div.options').forEach(function(div) {
        if(div.getAttribute('don') === 'right'){
            return;
        }
    var checkboxes = div.querySelectorAll('.exam-option-label input[type="checkbox"]');
    var allChecked = true;
    checkboxes.forEach(function(checkbox) {
        if(checkbox.getAttribute('typeos') !== 'answer' && checkbox.checked ) { 
            allChecked = false;
        }
        if (checkbox.getAttribute('typeos') === 'answer' && !checkbox.checked ) { 
            allChecked = false;
        }
    });
    if (allChecked) {
        div.parentNode.style.backgroundColor = '#e0f7ed';
        div.parentNode.setAttribute('ghj', 't');
    } else {
        div.parentNode.style.backgroundColor = '#ffebee';
        div.parentNode.setAttribute('ghj', 'f');
        var newbu = x_point_newbutt('查看解析', function (event) {
            helpful_answer_totellanyone((div.parentNode).getAttribute('tystatus'));
            event.stopPropagation();
        });
        div.parentNode.appendChild(newbu);
    }
});
}
function x_point_newbutt(content,func,duc){
    var button_new = document.createElement('button');
    button_new.innerText = content;
    button_new.className = 'gnxa-btn';
    button_new.onclick = func;
    if(duc === 1){
        button_new.style.marginRight = '90px';
    }
    return button_new;
}
function helpful_ai_open(gosbmnv){
    var quesyaks = document.querySelector(`[tystatus="${gosbmnv}"]`);
    var label1 = quesyaks.querySelectorAll('.professional-label');
    var answer = quesyaks.querySelector('textarea').value;
    layer.open({
        type: 1, 
        area: ['500px', '300px'],
        title: '判分',
        shade: 0.6, 
        shadeClose: true, 
        maxmin: true, 
        anim: 0, 
        content: ` 
        ${varible_qjstyle_ys}
        <label for="btdf_ai">AI打分</label>
        <input type="text" readonly id="btdf_ai" value="" >
        </br>
        <label for="btyj_ai">AI意见</label>
        <textarea type="text" readonly id="btyj_ai" value="" ></textarea>
        </br>
        <button id="buttons_ai"  type="button">申请AI打分</button>
        </br>
        <label for="btdf">本题得分</label>
        <input type="text" id="btdf" value="" >
        </br>
         <label for="btdfz">本题分数</label>
        <input type="text" readOnly id="btdfz" value="" >
        </br>
         <label for="btjx">本题解析</label>
        <textarea type="text" id="btjx" value="" ></textarea>
        </br>
            <button id="buttons"  type="button">修改</button>`,
        success: function (layero, index) {
            var dondothisdebug = false;
            document.getElementById('btdf').value = quesyaks.getAttribute('btdf');
            document.getElementById('btdfz').value = quesyaks.getAttribute('btdfz');
            document.getElementById('btjx').value = quesyaks.getAttribute('aians');
            document.getElementById('buttons_ai').onclick = function () {
                if(document.getElementById('btdfz').value === ''){
                    layer.msg('前先键入本题分数');
                    return;
                }
                document.getElementById('buttons_ai').disabled = true;
                layer.msg('已申请Ai打分,请稍等');
                helpful_ai_tochecktheanser(label1[1].innerText,answer,document.getElementById('btdfz').value);
            };       
            document.getElementById('buttons').onclick = function () {
                if(dondothisdebug){
                    document.getElementById('btdf').value = document.getElementById('btdfz').value;
                }
                if(document.getElementById('btdf').value === '' || document.getElementById('btdfz').value === ''){
                    layer.msg('请先输入分数');
                    return;
                }
                if(Number(document.getElementById('btdf').value) > Number(document.getElementById('btdfz').value)){
                    layer.msg('得分分值不能大于本题分数');
                    return;
                }
                quesyaks.setAttribute('btdf', document.getElementById('btdf').value);
                quesyaks.setAttribute('btdfz', document.getElementById('btdfz').value);
                quesyaks.setAttribute('aians', document.getElementById('btjx').value);
                if((quesyaks.querySelector('h3').innerText).split('(')){
                    quesyaks.querySelector('h3').innerText = quesyaks.querySelector('h3').innerText.split('(')[0]+'('+document.getElementById('btdf').value+'/'+document.getElementById('btdfz').value+'分)';
                }else{
                    quesyaks.querySelector('h3').innerText = quesyaks.querySelector('h3').innerText+'('+document.getElementById('btdf').value+'/'+document.getElementById('btdfz').value+'分)';
                }
                layer.close(index);
            }
        }
      });
}
function helpful_ai_open2(gosbmnv){
    var quesyaks = document.querySelector(`[tystatus="${gosbmnv}"]`);
    var label1 = quesyaks.querySelectorAll('.professional-label');
    layer.open({
        type: 1, 
        area: ['500px', '300px'],
        title: '判分',
        shade: 0.6, 
        shadeClose: true, 
        maxmin: true, 
        anim: 0, 
        content: ` 
        ${varible_qjstyle_ys}
        <label for="btdf">本题得分</label>
        <input type="text" id="btdf" value="" >
        </br>
         <label for="btdfz">本题分数</label>
        <input type="text" readOnly id="btdfz" value="" >
        </br>
         <label for="btjx">本题解析</label>
        <textarea type="text" id="btjx" value="" ></textarea>
        </br>
            <button id="buttons"  type="button">修改</button>`,
        success: function (layero, index) {
            var dondothisdebug = false;
            document.getElementById('btdf').value = quesyaks.getAttribute('btdf');
            document.getElementById('btdfz').value = quesyaks.getAttribute('btdfz');
            document.getElementById('btjx').value = quesyaks.getAttribute('aians');  
            document.getElementById('buttons').onclick = function () {
                if(dondothisdebug){
                    document.getElementById('btdf').value = document.getElementById('btdfz').value;
                }
                if(document.getElementById('btdf').value === '' || document.getElementById('btdfz').value === ''){
                    layer.msg('请先输入分数');
                    return;
                }
                if(Number(document.getElementById('btdf').value) > Number(document.getElementById('btdfz').value)){
                    layer.msg('得分分值不能大于本题分数');
                    return;
                }
                quesyaks.setAttribute('btdf', document.getElementById('btdf').value);
                quesyaks.setAttribute('btdfz', document.getElementById('btdfz').value);
                quesyaks.setAttribute('aians', document.getElementById('btjx').value);
                if((quesyaks.querySelector('h3').innerText).split('(')){
                    quesyaks.querySelector('h3').innerText = quesyaks.querySelector('h3').innerText.split('(')[0]+'('+document.getElementById('btdf').value+'/'+document.getElementById('btdfz').value+'分)';
                }else{
                    quesyaks.querySelector('h3').innerText = quesyaks.querySelector('h3').innerText+'('+document.getElementById('btdf').value+'/'+document.getElementById('btdfz').value+'分)';
                }
                layer.close(index);
            }
        }
      });
}
function helpful_answer_totellanyone(statust){ //生成解析
    var axios = 0;
    function gst(){
        axios = 1;
    }
    var quesyaks = document.querySelector(`[tystatus="${statust}"]`);
    var contentas = '';
    if(quesyaks.id === 'question_gst'){
        contentas = quesyaks.getAttribute('aians') === null ? gst() : quesyaks.getAttribute('aians');
    }else if(quesyaks.id === 'question_tkt'){
        var inputid = quesyaks.querySelector('input').id;
        contentas = (jsonqjtoputin[statust]).find(obj => obj.hasOwnProperty(inputid))[inputid]
    }else if(quesyaks.id === 'question_onechoice'){
        quesyaks.querySelectorAll(`input[type="radio"]`).forEach(function (element) {
            if (element.getAttribute('style') === 'background-color: rgb(0, 140, 255);' && element.getAttribute('typeos') === 'answer') {
                contentas = element.value;
            }
        });
    }else if(quesyaks.id === 'question_morechoice'){
        quesyaks.querySelectorAll(`input[type="checkbox"]`).forEach(function (element) {
            if (element.getAttribute('style') === 'background-color: rgb(0, 140, 255);' && element.getAttribute('typeos') === 'answer') {
                if ((element.value).includes(':checked')) {
                    contentas = contentas + (element.value).slice(0, -8) +'、';
                }else{
                    contentas = contentas + element.value+'、';
                }
            }
        });
    }else{
        contentas = quesyaks.getAttribute('aians');
    }
    axios === 1 ? layer.msg('此题暂无解析') :layer.alert('解析：'+contentas);
}
function point_alladdai(){ //AI判分
    var getgst = document.querySelectorAll(`div[id="question_gst"]`);
    getgst.forEach(function(gst) {
        var button_new = x_point_newbutt('AI判分', function() {
            helpful_ai_open(gst.getAttribute('tystatus'));
        },1);
        var button_new2 = x_point_newbutt('查看解析', function() {
            helpful_answer_totellanyone(gst.getAttribute('tystatus'));
        });
        gst.appendChild(button_new);
        gst.appendChild(button_new2);
    });
}
function gotthis_pointfirsttoset(){ //将分数打出
    var allQuestions = document.querySelectorAll(`div[class="question"]`);
    const idstoexcept = ['question_gst', 'question_paintin']; // 排除ID
    allQuestions.forEach(function (element) {
        if (!idstoexcept.includes(element.id)) { //筛选
            if(element.getAttribute('btdf') !== null || element.getAttribute('btdfz') !== null){
                if(!element.querySelector('h3').innerText.includes('(')){
                    if(element.getAttribute('style') === 'background-color: rgb(255, 235, 238);'){
                        element.querySelector('h3').innerText = element.querySelector('h3').innerText+'(0'+'/'+element.getAttribute('btdfz')+'分)';
                        element.setAttribute('btdf', 0);
                    }else{
                        element.querySelector('h3').innerText = element.querySelector('h3').innerText+'('+element.getAttribute('btdfz')+'/'+element.getAttribute('btdfz')+'分)';
                        element.setAttribute('btdf', element.getAttribute('btdfz'));
                    }
                }
            }
        }
    });
}
function allpaint_pointaddbutt(){ //绘画题
    var moudle = document.querySelector('[id="question_paintin"]');
    if(moudle){
        var allQuestions = document.querySelectorAll('[id="question_paintin"]');
        allQuestions.forEach(function (element) {
            var button_new = x_point_newbutt('判分', function() {
                helpful_ai_open2(element.getAttribute('tystatus'));
            },1);
            var button_new2 = x_point_newbutt('查看解析', function() {
                helpful_answer_totellanyone(element.getAttribute('tystatus'));
            });
            element.appendChild(button_new);
            element.appendChild(button_new2);
    });
    }
}
function coding_pointaddbutt(){ //代码题
    var moudle = document.querySelector('[id="question_codeins"]');
    if(moudle){
        var allQuestions = document.querySelectorAll('[id="question_codeins"]');
        allQuestions.forEach(function (element) {
            var button_new = x_point_newbutt('判分', function() {
                helpful_ai_open2(element.getAttribute('tystatus'));
            },1);
            var button_new2 = x_point_newbutt('查看解析', function() {
                helpful_answer_totellanyone(element.getAttribute('tystatus'));
            });
            element.appendChild(button_new);
            element.appendChild(button_new2);
    });
    }
}
 function loading_intoquescon(data,jsonr_rcheck){
    questionnaire.innerHTML = data[0].anscon;
    let jsonb = data[0].ansan;
    let jsonbx = JSON.parse(jsonb);
  var jsonObj = jsonbx;
  fillfromdatajson(jsonObj);
  allcheckboxzdpg();
  point_tktcheck(jsonr_rcheck);//填空题
  point_alladdai();
  allpaint_pointaddbutt(); //绘画题
  coding_pointaddbutt(); //代码题
  gotthis_pointfirsttoset(); //将分数打出
}
const nowid = document.getElementById('choslandna_saa').innerText;
function init_cshbeok(){
    const formData = new FormData();
      formData.append('nowid', nowid);
      fetch('exam/getfromother.php', {
          method: 'POST',
          body: formData
      })
      .then(function (response) {
          return response.json();
      }).then(function (data) {
          if(data.code === 1){
            let jsonb = data.result;
            var jsonObj = JSON.parse(jsonb);
            jsonqjtoputin = jsonObj;
              loading_intoquescon(data.data,jsonObj);
          }else{
              layer.alert('加载失败');
          }
          yhload.loadqr_hide('questionnaire');
      });   
  }
  yhload.loadqr_show('questionnaire');
init_cshbeok();
//**********保存 */
function savestep_one(){ //确保完成所有评分点
    var tsu = false;
    var allQuestions = document.querySelectorAll(`div[class="question"]`);
    for (var element of allQuestions) {
        if(element.id !== 'question_infortoget'){
            if (element.getAttribute('btdf') === null || element.getAttribute('btdfz') === null) {
                tsu = false;
                break; 
            }else{
                tsu = true;
            }
        }   
            }
    if(tsu){
        return true;
    }else{
        return false;
    }
}
function savestep_two(){ //获取此卷分数以及总分数
    var allQuestions = document.querySelectorAll(`div[class="question"]`);
    var math_point = 0;
    var math_point_all = 0;
    allQuestions.forEach(function (element) {
        if(element.getAttribute('btdf') !== null && element.getAttribute('btdfz') !== null){
            var point_add = Number(element.getAttribute('btdf'));
            var zpoint_add = Number(element.getAttribute('btdfz'));
            math_point = math_point + point_add;
            math_point_all = math_point_all + zpoint_add;
        }
     })
     return [math_point, math_point_all];
}

function saveexamnowin(){
    if(!savestep_one()){
        layer.msg('请先完成所有题目的评分');
        return;
    }
    var math_point = savestep_two();
    let allhtml = questionnaire.innerHTML;
    const formData = new FormData();
    formData.append('allhtml', allhtml);
    formData.append('nowid', nowid);
    formData.append('score', math_point);
    fetch('exam/keepnew_y.php', {
        method: 'POST',
        body: formData
    })
    .then(function (response) {
        return response.json();
    }).then(function (data) {
        if(data.status === 200){
            layer.alert('保存成功');
            setTimeout(function(){window.location.href = './';},2000);
        }else{
            layer.alert('保存失败');
        }
    });   
}